package wsi.gui.function.select;

import java.util.List;

import javax.swing.tree.DefaultTreeModel;

import org.rygh.core.face.IHasValue;

import wsi.function.Function;
import wsi.function.FunctionController;
import wsi.ws.WebServices;

public class FunctionRoot implements IHasValue<FunctionNode> {

	private final FunctionNode root = new FunctionNode(null, null);

	public FunctionRoot() {

	}

	public DefaultTreeModel getModel() {
		return new DefaultTreeModel(root);
	}

	@Override
	public FunctionNode getValue() {
		return root;
	}

	public void load() {
		root.removeAllChildren();

		FunctionNode parent, node;
		int a, count = 0;
		List<Function> functions;

		FunctionController fctrl = FunctionController.shared();

		fctrl.load();

		for (WebServices service : WebServices.values()) {
			functions = fctrl.getFunctions(service.name());

			a = functions.size();
			count += a;

			parent = new FunctionNode(String.format("%s (%d)", service, a),
					null);
			root.add(parent);

			for (Function func : functions) {
				node = new FunctionNode(func.getName(), func);
				parent.add(node);
			}
		}

		root.setName(String.format("%d function(s)", count));
	}
}
